/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.sharding.client.listener;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.lvyh.lightframe.sharding.client.property.NacosProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;

import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * @author lvyh 2021/11/02.
 */
public class NacosDatasourceInfo {
    private static Logger logger = LoggerFactory.getLogger(NacosDatasourceInfo.class);

    private static final String DATA_ID = "mysql";

    private static final String GROUP_ID = "DEFAULT_GROUP";

    private ApplicationEventPublisher applicationEventPublisher;

    private NacosProperty nacosProperty;

    public NacosDatasourceInfo(ApplicationEventPublisher applicationEventPublisher, NacosProperty nacosProperty) {
        this.applicationEventPublisher = applicationEventPublisher;
        this.nacosProperty = nacosProperty;
        addListener();
    }

    /**
     * Add nacos listener
     */
    private void addListener() {
        try {
            String serverAddr = nacosProperty.getUrl();
            String dataId = nacosProperty.getDataId();
            String groupId = nacosProperty.getGroupId();
            Properties properties = new Properties();
            properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
            ConfigService configService = NacosFactory.createConfigService(properties);
            String content = configService.getConfig(dataId, groupId, 5000);
            //logger.info("print data source: " + content);

            //Register listening
            configService.addListener(dataId, groupId, new Listener() {
                @Override
                public void receiveConfigInfo(String configInfo) {
                    applicationEventPublisher.publishEvent(new RefreshDatasourceEvent(configInfo));
                    logger.info("nacos config has updated, ready to refresh data. new data:{}", configInfo);
                }

                @Override
                public Executor getExecutor() {
                    return null;
                }
            });


        } catch (NacosException e) {
            logger.error("nacos register data listener error", e);
        }
    }
}
